import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from RA_Cal import csvtest

def make_monotonic(arr):
    arr = np.array(arr).astype(float)  # 转为浮点数组避免整数问题
    if len(arr) == 0:
        return arr

    for i in range(1, len(arr)):
        if arr[i] <= arr[i - 1]:
            arr[i] = arr[i - 1] + 1e-8  # 微小增量保证严格递增
    return arr

import os
# 获取当前文件的父文件夹路径
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(parent_dir)

XX = csvtest.Read_csv_inrows(parent_dir+"\DPGA_new\CURVE_DPGA_adpt_1.csv", [0])[:, 0]
yy = csvtest.Read_csv_inrows(parent_dir+"\DPGA_new\CURVE_DPGA_adpt_1.csv", [1])[:, 0]

# XX = csvtest.Read_csv_inrows(parent_dir+"\GA\GAnew_result_0.csv", [0])[:, 0]
# yy = csvtest.Read_csv_inrows(parent_dir+"\GA\GAnew_result_0.csv", [1])[:, 0]

# XX = csvtest.Read_csv_inrows(parent_dir+"\GAMp\GAMP_result_0.csv", [0])[:, 0]
# yy = csvtest.Read_csv_inrows(parent_dir+"\GAMp\GAMP_result_0.csv", [1])[:, 0]
XX = np.array(XX, dtype=int)
# 示例数据加载（替换为你的实际数据）
data = {
    "ID": XX,
    "Value": yy
}

df = pd.DataFrame(data).sort_values("ID")  # 按ID排序

# 参数设置
step = 500  # ID分组步长
min_id, max_id = df["ID"].min(), df["ID"].max()
id_bins = range(min_id, max_id + step, step)  # 生成分组区间（如1-10, 11-20,...）

# 按步长分组并计算统计量
df["ID_Group"] = pd.cut(df["ID"], bins=id_bins, right=False)  # 左闭右开区间
grouped = df.groupby("ID_Group")["Value"]
median_curve = grouped.median()
upper_curve = grouped.max()  # 或 quantile(0.95)
lower_curve = grouped.min()  # 或 quantile(0.05)

# upp_arr = upper_curve.values
# median_arr = median_curve.values
# low_arr = lower_curve.values

upp_arr = make_monotonic(upper_curve.values)
median_arr = make_monotonic(median_curve.values)
low_arr = make_monotonic(lower_curve.values)

# 获取分组区间的中点作为横坐标（更美观）
x_labels = [f"{int(b.left)}-{int(b.right)-1}" for b in median_curve.index]
x_pos = np.array([b.mid for b in median_curve.index])

# 绘图
plt.figure(figsize=(12, 6))
plt.scatter(XX, yy)
plt.plot(x_pos, median_arr, color="blue", linestyle="-")
plt.plot(x_pos, upp_arr,  color="red", linestyle="--")
plt.plot(x_pos, low_arr, color="green", linestyle="--")

# 图表美化
plt.xlabel("ID", fontsize=12)
plt.ylabel("Fitness", fontsize=12)
# plt.xticks(x_pos, x_pos, rotation=45)  # 横轴显示分组标签
plt.legend()
plt.grid(True, linestyle="--", alpha=0.6)
plt.tight_layout()  # 避免标签重叠
plt.show()

# import csv
# with open("zcc0.csv", 'a', encoding='utf-8', newline='') as f:
#     write = csv.writer(f)
#     write.writerow(list(2500 + x_pos))
#     write.writerow(list(-median_arr))
#     write.writerow(list(-upp_arr))
#     write.writerow(list(-low_arr))

